package de.nordakademie.wpk.share.core.data.datastorage.depot;

import java.util.List;

import de.nordakademie.wpk.share.core.data.Depot;
import de.nordakademie.wpk.share.core.data.Share;
import de.nordakademie.wpk.share.core.service.ShareService;

/**
 * This container inherits all depots and indices used in the application with
 * the current data.
 * 
 * @author Christian Baumhof
 */
public class DepotContainer {

	private List<Depot> depots;

	public DepotContainer() {
		initDepots();
	}

	public List<Depot> getDepots() {
		return depots;
	}

	public void saveOrUpdateDepot(Depot newDepot) {
		if (isUnusedId(newDepot.getId())) {
			depots.add(newDepot);
		} else {
			for (Depot depot : depots) {
				if (depot.getId() == newDepot.getId()) {
					depot = newDepot;
					break;
				}
			}
		}
	}

	public void deleteDepot(Depot deleteDepot) {
		if (!isUnusedId(deleteDepot.getId())) {
			for (Depot depot : depots) {
				if (depot.getId() == deleteDepot.getId()) {
					depots.remove(depots.indexOf(depot));
					break;
				}
			}
		}
	}

	/**
	 * Returns a new id for a new depot or index
	 * 
	 * @return Integer
	 */
	public Integer getUnusedId() {
		int id = 0;
		while (!isUnusedId(id)) {
			id++;
		}
		return id;
	}

	/**
	 * Refreshes data
	 */
	public void refreshDepotData() {
		for (Depot depot : depots) {
			for (Share share : depot.getShares()) {
				share.setAnnRange(ShareService.shareContainer.getShareBySymbol(
						share.getSymbol()).getAnnRange());
				share.setPercentageChange(ShareService.shareContainer
						.getShareBySymbol(share.getSymbol())
						.getPercentageChange());
				share.setQuotation(ShareService.shareContainer
						.getShareBySymbol(share.getSymbol()).getQuotation());
				share.setHistoricQuotes(ShareService.shareContainer
						.getShareBySymbol(share.getSymbol())
						.getHistoricQuotes());
			}
		}
	}

	/**
	 * Returns true if a depot with the given name already exists, otherwise
	 * false
	 * 
	 * @param depotName
	 * @return Boolean
	 */
	public Boolean isUnique(String depotName) {
		for (Depot depot : depots) {
			if (depot.getName().equals(depotName)) {
				return false;
			}
		}
		return true;
	}

	private void initDepots() {
		depots = SupportedIndices.getSupportedIndices();
	}

	private Boolean isUnusedId(Integer id) {
		for (Depot depot : depots) {
			if (depot.getId() == id) {
				return false;
			}
		}
		return true;
	}

}
